package com.ljfiction.book.MyView;

import android.content.Context;
import android.os.Parcelable;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.SparseArray;


import com.ljfiction.book.tools.Tool;
import com.rey.material.widget.EditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by QAQ on 2016/12/13.
 */

public class ContainsEmojiEditText extends EditText {
    //输入表情前的光标位置
    private int cursorPos;
    //输入表情前EditText中的文本
    private String inputAfterText;
    //是否重置了EditText的内容
    private boolean resetText;

    private Context mContext;
    private Pattern pattern;

    public ContainsEmojiEditText(Context context) {
        super(context);
        this.mContext = context;
        initEditText();
    }

    public ContainsEmojiEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;

        initEditText();
    }

    public ContainsEmojiEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initEditText();
    }

    // 初始化edittext 控件
    private void initEditText() {
        //pattern = Pattern.compile("[^a-zA-Z0-9\\u4E00-\\u9FA5_,.\\uFEFF\\u200C″?\\s!\\\\:∶：;…~_\\-\"\"/@*+'()<>{}/[/]()<>{}\\[\\]=%&$|\\/♀♂#¥£¢€\"^`●•¡£¢∞§¶•ªº–≠，。？│！：；……～“”、“（）”、（——）‘’＠‘·’＆＊＃《》￥《〈〉》〈＄〉［］￡［］｛｝｛｝￠【】【】％〖〗〖〗／〔〕〔〕＼『』『』＾「」「」｜﹁﹂｀．～＇ⅠⅡⅢⅣⅤⅥⅦⅧⅨ]");
        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    cursorPos = getSelectionEnd();
                    // 这里用s.toString()而不直接用s是因为如果用s，
                    // 那么，inputAfterText和s在内存中指向的是同一个地址，s改变了，
                    // inputAfterText也就改变了，那么表情过滤就失败了
                    inputAfterText= s.toString();
                }

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    /*Matcher matcher=  pattern.matcher(s);
                    if(!matcher.find()){

                    }else{
                        resetText = true;
                        Tool.showToast("不支持输入Emoji表情符号和颜文字",mContext);
                        //是表情符号就将文本还原为输入表情符号之前的内容
                        setText(inputAfterText);
                        CharSequence text = getText();
                        if (text instanceof Spannable) {
                            Spannable spanText = (Spannable) text;
                            Selection.setSelection(spanText, text.length());
                        }
                    }*/
                    if (count-before >= 2) {//表情符号的字符长度最小为2
                        CharSequence input = s.subSequence(start+before, start + count);
                        if (containsEmoji(input.toString())) {
                            resetText = true;
                            Tool.showToast("不支持输入Emoji表情符号",mContext);
                            //是表情符号就将文本还原为输入表情符号之前的内容
                            setText(inputAfterText);
                            CharSequence text = getText();
                            if (text instanceof Spannable) {
                                Spannable spanText = (Spannable) text;
                                Selection.setSelection(spanText, text.length());
                            }
                        }
                    }
                } else {

                    resetText = false;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }
    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);
        ss.childrenStates = new SparseArray();
        //注释部分是代码中存的一些数据
        //  ss.childrenStates.put(INSTANCE_TEXT_COLOR, getTextColor());
        //  ss.childrenStates.put(INSTANCE_TEXT_SIZE, getProgressTextSize());
        //  ss.childrenStates.put(INSTANCE_REACHED_BAR_HEIGHT, getReachedBarHeight());
        //  ss.childrenStates.put(INSTANCE_TEXT_VISIBILITY, getProgressTextVisibility());
        return ss;
    }
    @Override
    public void onRestoreInstanceState(Parcelable state) {
        if (state == null) return ;
        if (state instanceof SavedState){
            SavedState ss = (SavedState) state;
            if (ss != null  && ss.childrenStates != null) {
                SparseArray childrenStates = ss.childrenStates;
                //  mTextColor = (int) childrenStates.get(INSTANCE_TEXT_COLOR);
                //  mTextSize = (float) childrenStates.get(INSTANCE_TEXT_SIZE);
            }
            super.onRestoreInstanceState(state);
        }
    }


    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }
}
